<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Order as OrderService;
use app\common\service\Material as MaterialService;
use app\common\service\TTask as TTaskService;
use app\common\service\TTaskLog as TTaskLogService;
use app\common\service\TTaskAttention as TTaskAttentionService;
use app\common\service\TTaskRights as TTaskRightsService;
use app\common\service\TProject as TProjectService;
use \app\common\service\SystemUser as SystemUserService;
/**
 * 任务管理
 * @author King
 *
 */
class TTask extends Admin
{
	protected $hisiValidate = 'TTask';

    public function initialize() {
    	parent::initialize();

    	$projectKV = (new TProjectService())->getList(null);
    	$this->assign('projectKV', $projectKV);
    }

    /**
     * 任务列表
     *
     * @author King
     * @date 2020年8月21日
     *
     * @return string
     */
    public function index()
    {
		if ($this->request->isAjax()) {
			$projectId = $this->request->param('project_id/d', 0);
			$type = $this->request->param('type/d', 0);	// 0全部，1我创建，2我参与，3我关注
			$order = $this->request->param('order/s', 'priority');	// 优先级，创建时间，更新时间

			$result = [];
			$where = [];
			$whereJoin = "1=1";
			if ($projectId) $where[] = ['project_id', '=', $projectId];
			if ($type == 1) $where[] = ['admin_id', '=', ADMIN_ID];
			elseif ($type == 2) {
				$where[] = ['admin_id', '<>', ADMIN_ID];
				$whereJoin = "FIND_IN_SET(".ADMIN_ID.", join_admin_ids)";
			}
			elseif ($type == 3) $where[] = ['id', 'in', db('t_task_attention')->where('admin_id', ADMIN_ID)->column('task_id')];

			$field = "id,name,client_ordernum,material_id,material_sku,priority,create_time,update_time";

			$result['todoNum'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 1)->count(1);
			$result['todoList'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 1)->field($field)->order($order, 'desc')->select();

			$result['doingNum'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 2)->count(1);
			$result['doingList'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 2)->field($field)->order($order, 'desc')->select();

			$result['doneNum'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 3)->count(1);
			$result['doneList'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 3)->field($field)->order("create_time", 'desc')->limit(50)->select();

			$result['pauseNum'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 4)->count(1);
			$result['pauseList'] = db('t_task')->where($where)->whereRaw($whereJoin)->where('status', 4)->field($field)->order($order, 'desc')->select();

			$tTaskService = new TTaskService();
			$tTaskRightsService = new TTaskRightsService();
			$allKeyList = ['todoList', 'doingList', 'doneList', 'pauseList'];
			foreach ($allKeyList as $val) {
				foreach ($result[$val] as $k => $v) {
					$taskId = $v['id'];

					$result[$val][$k]['progressLastAdminInfo'] = $tTaskService->getProgressLastAdminInfo($taskId);

					$roleId = $tTaskRightsService->getTaskRoleId($taskId);

					// 是否可修改状态
					$result[$val][$k]['canChangeStatus'] = $tTaskRightsService->checkCanChangeStatus($taskId, $roleId);

					// 是否可关注
					$result[$val][$k]['canAttention'] = $tTaskRightsService->checkCanAttention($taskId, $roleId);

					// 是否可编辑
					$result[$val][$k]['canEdit'] = $tTaskRightsService->checkCanEdit($taskId, $roleId);

					// 是否可删除
					$result[$val][$k]['canDel'] = $tTaskRightsService->checkCanDel($taskId, $roleId);

					// 是否已关注
					$result[$val][$k]['isAttention'] = $tTaskService->checkIsAttention($taskId);

					// 获取评论数
					$result[$val][$k]['commentNum'] = $tTaskService->getCommentNum($taskId);

				}
			}

			return $this->Json(1, '', $result);
		}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 任务详情
     */
    public function detail() {
    	$taskId = $this->request->param('id/d', 0);
		$systemUserService=new SystemUserService();
		$systemUserKV = getSystemUserKV(null);
    	$tProjectService = new TProjectService();
    	$tTaskService = new TTaskService();
    	$tTaskRightsService = new TTaskRightsService();
		$tTaskLogService = new TTaskLogService();
		$materialService = new MaterialService();
    	$ttInfo = $tTaskService->getInfoById($taskId);		
		$systemUserVK = $systemUserService->getVKList(null);
		$page       = $this->request->param('page/d', 1);
		$limit      = $this->request->param('limit/d', 5);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}
		$materialInfo=$materialService->getInfoBySku($ttInfo['material_sku']);
		if(empty($materialInfo)){
			$materialInfo=[
				'name'=>'',
				'color'=>'',
			];
		}
    	$rightsInfo = [];
    	$roleId = $tTaskRightsService->getTaskRoleId($taskId);
    	// 是否可修改状态
    	$rightsInfo['canChangeStatus'] = $tTaskRightsService->checkCanChangeStatus($taskId, $roleId);
    	// 是否可修改进度
    	$rightsInfo['canChangeProgress'] = $tTaskRightsService->checkCanChangeProgress($taskId, $roleId);
    	// 是否可编辑
    	$rightsInfo['canEdit'] = $tTaskRightsService->checkCanEdit($taskId, $roleId);
    	// 是否可删除
    	$rightsInfo['canDel'] = $tTaskRightsService->checkCanDel($taskId, $roleId);
    	// 是否可发布评论
    	$rightsInfo['canCommentCreate'] = $tTaskRightsService->checkCommentCreate($taskId, $roleId);
		//获取评论
		$rightsInfo['comment']=db('t_task_comment')->where('task_id', $taskId)->order('update_time desc')->where('status', 1)->select();
		foreach ($rightsInfo['comment'] as $key => $value) {
			$a=str_replace('&lt;','<',$value['content']);
			$b=str_replace('&gt;','>',$a);
			$c=str_replace('&quot;','"',$b);
			$d=str_replace('nbsp;','',$c);
			$e=str_replace('&amp;',' ',$d);
			$rightsInfo['comment'][$key]['content']=$e;
			$rightsInfo['comment'][$key]['nick']= arrayGet($systemUserKV, $rightsInfo['comment'][$key]['admin_id'],'');	
		}
    	// 获取评论数
    	$rightsInfo['commentNum'] = $tTaskService->getCommentNum($taskId);
		
    	
    	$assign = [
			'materialInfo'=>$materialInfo,
    		'ttInfo' => $ttInfo,
    		'rightsInfo' => $rightsInfo,
    		'creator' => arrayGet($systemUserKV, $ttInfo['admin_id'], ''),
    		'projectUserList' => $tProjectService->getUsersByProjectId($ttInfo['project_id'], [1,2,3]),
    		'progressList' => $tTaskService->getProgressList($taskId),
			'systemUserKV'=>$systemUserKV
    	];		
    	return $this->assign($assign)->fetch();
    }

    /**
     * 新建任务
     */
    public function add() {
    	if ($this->request->isAjax()) {
    		$postData = $this->request->post();
    		$projectId = $this->request->param('project_id/d', 0);
    		$name = $this->request->param('name/s', '');
    		$clientOrdernum = $this->request->param('client_ordernum/s', '');
    		$materialSku = $this->request->param('material_sku/s', '');
    		$content = $this->request->param('content/s', '');
    		$priority = $this->request->param('priority/d', 2);

    		if ($this->hisiValidate) {// 数据验证

    			if (strpos($this->hisiValidate, '\\') === false) {
    				if (defined('IS_PLUGINS')) {
    					$this->hisiValidate = 'plugins\\' . $this->request->param('_p') . '\\validate\\' . $this->hisiValidate;
    				} else {
    					$this->hisiValidate = 'app\\' . $this->request->module() . '\\validate\\' . $this->hisiValidate;
    				}
    			}
    			if ($this->hisiAddScene) {
    				$this->hisiValidate = $this->hisiValidate . '.' . $this->hisiAddScene;
    			}
    			$result = $this->validate($postData, $this->hisiValidate);
    			if ($result !== true) {
    				return $this->error($result);
    			}
    		}

    		$orderService = new OrderService();
    		$materialService = new MaterialService();
    		$tTaskLogService = new TTaskLogService();
    		if ($clientOrdernum != '') {
    			$oInfo = $orderService->getInfoByClientOrdernum($clientOrdernum, 'id');
    			if (empty($oInfo)) {
    				return $this->error('订单号不存在');
    			}
    		}
    		$materialId = 0;
    		if ($materialSku != '') {
    			$mInfo = $materialService->getInfoBySku($materialSku, 'id');
    			if (empty($mInfo)) {
    				return $this->error('物料SKU不存在');
    			}
    			$materialId = $mInfo['id'];
    		}

    		try {
    			db()->startTrans();
    			// 入库
    			$insData = [
    				'project_id' => $projectId,
    				'name' => $name,
    				'client_ordernum' => $clientOrdernum,
    				'material_id' => $materialId,
    				'material_sku' => $materialSku,
    				'content' => $content,
    				'priority' => $priority,
    				'admin_id' => ADMIN_ID,
    				'join_admin_ids' => ADMIN_ID,
    				'status' => 1,
    				'create_time' => time(),
    				'update_time' => time(),
    			];
    			$taskId = db('t_task')->insertGetId($insData);

    			// 记录操作日志
    			$tTaskLogService->addLog($taskId, 1, '新建了任务['.$name.']');

    			db()->commit();

    			return $this->Json(1,"操作成功");
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch('form');
    }

    /**
     * 编辑任务
     */
    public function edit() {
    	$id = $this->request->param('id/d', 0);
    	$tTaskService = new TTaskService();
    	$ttInfo = $tTaskService->getInfoById($id);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	if ($this->request->isAjax()) {
    		$postData = $this->request->post();
    		$projectId = $this->request->param('project_id/d', 0);
    		$name = $this->request->param('name/s', '');
    		$clientOrdernum = $this->request->param('client_ordernum/s', '');
    		$materialSku = $this->request->param('material_sku/s', '');
    		$content = $this->request->param('content/s', '');
    		$priority = $this->request->param('priority/d', 2);

    		if ($this->hisiValidate) {// 数据验证

    			if (strpos($this->hisiValidate, '\\') === false) {
    				if (defined('IS_PLUGINS')) {
    					$this->hisiValidate = 'plugins\\' . $this->request->param('_p') . '\\validate\\' . $this->hisiValidate;
    				} else {
    					$this->hisiValidate = 'app\\' . $this->request->module() . '\\validate\\' . $this->hisiValidate;
    				}
    			}
    			if ($this->hisiAddScene) {
    				$this->hisiValidate = $this->hisiValidate . '.' . $this->hisiAddScene;
    			}
    			$result = $this->validate($postData, $this->hisiValidate);
    			if ($result !== true) {
    				return $this->error($result);
    			}
    		}

    		$orderService = new OrderService();
    		$materialService = new MaterialService();
    		$tTaskLogService = new TTaskLogService();

    		if ($clientOrdernum != '') {
    			$oInfo = $orderService->getInfoByClientOrdernum($clientOrdernum, 'id');
    			if (empty($oInfo)) {
    				return $this->error('订单号不存在');
    			}
    		}
    		$materialId = 0;
    		if ($materialSku != '') {
    			$mInfo = $materialService->getInfoBySku($materialSku, 'id');
    			if (empty($mInfo)) {
    				return $this->error('物料SKU不存在');
    			}
    			$materialId = $mInfo['id'];
    		}

    		try {
    			db()->startTrans();
    			// 入库
    			$upData = [
    				'project_id' => $projectId,
    				'name' => $name,
    				'client_ordernum' => $clientOrdernum,
    				'material_id' => $materialId,
    				'material_sku' => $materialSku,
    				'content' => $content,
    				'priority' => $priority,
    				'update_time' => time(),
    			];
    			$taskId = db('t_task')->where('id', $id)->update($upData);

    			// 记录操作日志
    			$tTaskLogService->addLog($taskId, 1, '修改了任务['.$name.']');

    			db()->commit();

    			return $this->Json(1);
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}

    	$assign = [
    		'formData' => $ttInfo,
    	];
    	return $this->assign($assign)->fetch('form');
    }

    /**
     * 关注任务
     */
    public function attention() {
    	$taskId = $this->request->param('id/d', 0);

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();
    	$tTaskAttentionService = new TTaskAttentionService();

    	$ttInfo = $tTaskService->getInfoById($taskId, 'id,project_id');
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}
    	$attentionId = $tTaskAttentionService->checkIsAttention($taskId);
    	if ($attentionId) {
			db('t_task_attention')->where('id', $attentionId)->delete();
			$isAttention = 0;
		} else {
			$insData = [
				'project_id' => $ttInfo['project_id'],
				'task_id' => $taskId,
				'admin_id' => ADMIN_ID,
				'create_time' => time(),
			];
			db('t_task_attention')->insertGetId($insData);
			$isAttention = 1;
		}
		return $this->Json(1, '', ['taskId' => $taskId, 'isAttention' => $isAttention]);
    }

    /**
     * 删除任务
     */
    public function del() {
    	$taskId = $this->request->param('id/d', 0);

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();

    	$ttInfo = $tTaskService->getInfoById($taskId, 'id,name');
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	try {
    		db()->startTrans();
    		// 入库
    		$upData = [
    			'status' => 0,
    			'update_time' => time(),
    		];
    		db('t_task')->where('id', $taskId)->update($upData);

    		// 记录操作日志
    		$tTaskLogService->addLog($taskId, 1, '删除了任务['.$ttInfo['name'].']');

    		db()->commit();

    		return $this->Json(1, '', ['taskId' => $taskId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 任务流转
     */
    public function progress() {
    	$taskId = $this->request->param('id/d', 0);
    	$adminId = $this->request->param('admin_id/d', 0);
    	$assistAdminIds = $this->request->param('assist_admin_ids/a', []);
    	$remark = $this->request->param('remark/s', '');

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();

    	$ttInfo = $tTaskService->getInfoById($taskId);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	try {
    		db()->startTrans();

    		// 判断当前负责人是否自己
    		if($tTaskService->getProgressLastAdminId($taskId) == $adminId) {
    			throw new \Exception('当前已是该用户负责');
    		}

    		$upData = [
    			'update_time' => time(),
    		];
    		// 追加参与人
    		$joinAdminIds = explode(',', arrayGet($ttInfo, 'join_admin_ids', ''));
    		if (!in_array($adminId, $joinAdminIds)) {
    			array_push($joinAdminIds, $adminId);
    			$upData['join_admin_ids'] = implode(',', $joinAdminIds);
    		}
    		db('t_task')->where('id', $ttInfo['id'])->update($upData);

    		$systemUserKV = getSystemUserKV(null);

    		// 入库
    		$insData = [
    			'project_id' => $ttInfo['project_id'],
    			'task_id' => $taskId,
    			'admin_id' => $adminId,
    			'assist_admin_ids' => implode(',', $assistAdminIds),
    			'remark' => $remark,
    			'create_time' => time(),
    			'update_time' => time(),
    		];
    		$progressId = db('t_task_progress')->insertGetId($insData);

    		// 记录操作日志
    		$tTaskLogService->addLog($taskId, 3, arrayGet($systemUserKV, ADMIN_ID, '') . '将任务['.$ttInfo['name'].']指派给 ' . arrayGet($systemUserKV, $adminId, ''));

    		db()->commit();

    		return $this->Json(1, '', ['taskId' => $taskId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 修改任务状态
     */
    public function status() {
    	$taskId = $this->request->param('id/d', 0);
    	$status = $this->request->param('status/d', 0);

    	$tTaskLogService = new TTaskLogService();
    	$tTaskService = new TTaskService();

    	$ttInfo = $tTaskService->getInfoById($taskId, 'id,name');
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}

    	try {
    		db()->startTrans();
    		// 入库
    		$upData = [
    			'status' => $status,
    			'update_time' => time(),
    		];
    		db('t_task')->where('id', $taskId)->update($upData);

    		// 记录操作日志
    		$tTaskLogService->addLog($taskId, 1, '修改了任务['.$ttInfo['name'].']状态为' . arrayGet(config('mimo.task_status'), $status, ''));

    		db()->commit();

    		return $this->Json(1, '', ['taskId' => $taskId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }
	/**
     * 增加评论
     */
	public function addComment() {
		$taskId = $this->request->param('id/d', 0);
		$systemUserService=new SystemUserService();
		$systemUserKV = getSystemUserKV(null);
    	$tProjectService = new TProjectService();
    	$tTaskService = new TTaskService();
		$tTaskLogService = new TTaskLogService();
		$ttInfo = $tTaskService->getInfoById($taskId);
		$systemUserVK = $systemUserService->getVKList(null);
    	if (empty($ttInfo)) {
    		return $this->error('任务不存在');
    	}
		if ($this->request->isPost()) {
    		$postData = $this->request->post();
    		$content = $this->request->param('content/s', '');
			$result = array(); 
			preg_match_all ("/&gt;@(.*)\&lt/U", $content, $result);			
			$atAdminIds=[];
			foreach ($result[1] as $key => $value) {
				$atAdminIds[]= arrayGet($systemUserVK, $value, '');
			}
			$atAdminIds = implode(",", $atAdminIds);
			//新增评论
			try {
    			db()->startTrans();
				$CommentData=[
					'project_id' => $ttInfo['project_id'],
					'task_id' => $ttInfo['id'],
					'content' => $content,
					'admin_id' => ADMIN_ID,
					'at_admin_ids'=>$atAdminIds,
					'create_time' => time(),
					'update_time' => time(),
				];
				$commentId = db('t_task_comment')->insertGetId($CommentData);
				//更新任务时间
				db('t_task')->where('id',$ttInfo['id'])->update(['update_time'=>time()]);
    			// 记录操作日志
    			$tTaskLogService->addLog($commentId, 2, '新增了任务['.$ttInfo['name'].']的评论');

    			db()->commit();

    			return $this->Json(1,"操作成功");
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
		}
	}

    //导出任务列表
	public function exportTask(){
        $where[]=['t.status','<',99];
        $systemUserKV = getSystemUserKV(null);
        $tasklist=db('t_task t')
            ->join("t_project p", 'p.id = t.project_id','left')->field("t.*,p.name as projectname")->order('t.id desc')
            ->where($where)->select();
        foreach ($tasklist as $key=>&$v){
            $logList=db('t_task_log')->where('task_id', $v['id'])->order('create_time asc')->select();
            $v['checktime']=$v['actiontime']=$v['finishtime']='';
            foreach ($logList as $key => &$value) {
                if(strpos($value['remark'],'批了任务通过')!==false && $v['checktime']==''){
                    $v['checktime']=date("Y-m-d H:i",$value['create_time']);
                }
                if(strpos($value['remark'],'进行中')!==false && $v['actiontime']==''){
                    $v['actiontime']=date("Y-m-d H:i",$value['create_time']);
                }
                if(strpos($value['remark'],'已完成')!==false && $v['finishtime']==''){
                    $v['finishtime']=date("Y-m-d H:i",$value['create_time']);
                }
            }
            $v['create_time']=date("Y-m-d H:i",$v['create_time']);
            $v['adminname']= arrayGet($systemUserKV,$v['admin_id'],'');
            $v['actionuser']= arrayGet($systemUserKV,$v['execute_uid'],'');
            $result=explode(',',$v['join_admin_ids']);
            $atAdminIds=[];
            foreach ($result as $key => $value) {
                $atAdminIds[]= arrayGet($systemUserKV, $value, '');
            }
            $atAdminIds = implode(" , ", $atAdminIds);
            $v['join_admins']=$atAdminIds;
        }
        $assign = [
            'tasklist' => $tasklist
        ];
        return $this->assign($assign)->fetch();
    }
}